<?php

namespace App\Wechat;

use App\Models\Appoint;
use App\Models\Article;
use App\Models\ArticleInfo;
use App\Models\Family;
use App\Models\FamilyEdu;
use App\Models\Hospital;
use App\Models\HospitalAppointInterval;
use App\Models\HospitalAppointType;
use App\Models\InterviewRemind;
use App\Models\Notice;
use App\Models\ScanRecord;
use App\Models\SubMessage;
use App\Models\TempPushRecord;
use App\Models\User;
use App\Models\UserLogin;
use App\Services\WeChat\TemplateFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Psr16Cache;

class MiniTemp
{

    /**
     * 模板消息url
     * @var string
     */
    private static $sendUrl = "/cgi-bin/message/subscribe/send";
    private $user_id;
    private $mini_appid;
    private $api;
    private $miniprogram;
    private $openid;
    private $template_id;
    private $url="";
    private $client_msg_id="";

    public function __construct(TempPushRecord $tempPushRecord)
    {

        $temp = \App\Models\Temp::query()->where('id', $tempPushRecord->temp_id)->first();
        if($temp) {
            $this->function_name = $temp->function_name;
            $this->template_id = $temp->mini_template_id;
            $this->setOpenid($tempPushRecord->user_id);
            $this->url = $temp->path;
            $this->user_id = $tempPushRecord->user_id;
        }else{
            throw new \Exception($tempPushRecord->temp_id."模板不存在");
        }
    }
    public function send(Model $model)
    {
        $function = $this->function_name;;
        return $this->$function($model);
    }

    public function setOpenid($user_id)
    {
        $openid = UserLogin::query()
            ->where('user_id',$user_id)
            ->value('openid');
//        if(!$openid) {
//            $openid = ScanRecord::query()
//                ->where('user_id', $user_id)
//                ->where('xopenid', '!=', '')
//                ->value('xopenid');
//        }

        $this->openid = $openid;

    }

    /**
     * 预约成功通知
     * @param Appoint $appoint
     * @return $this
     * @throws \Exception
     */
    public function AppointDone(Appoint $appoint)
    {
        $type = HospitalAppointType::query()->where('id',$appoint->type)->value('name');
        $appoint_time = HospitalAppointInterval::query()->where('id',$appoint->appoint_time)->first();

        $template = app(TemplateFactory::class)
            ->create('appoint_success')
            ->to($this->openid)
            ->name($appoint->family->name)
            ->type($type)
            ->hospital(Str::substr($appoint->hospital->name,0,20))
            ->datetime($appoint->appoint_date." ".isset($appoint_time)?$appoint_time->start."-".$appoint_time->end:"")
            ->date($appoint->appoint_date);
        $template->send();

        return '';
    }

    /**
     * 预约失败通知
     * @param Appoint $appoint
     * @return $this
     * @throws \Exception
     */
    public function AppointCancel(Appoint $appoint)
    {
        $type = HospitalAppointType::query()->where('id',$appoint->type)->value('name');
        $template = app(TemplateFactory::class)
            ->create('appoint_fail')
            ->to($this->openid)
            ->name($appoint->family->name)
            ->type($type)
            ->hospital(Str::substr($appoint->hospital->name,0,20))
            ->datetime($appoint->appoint_date)
            ->info('号源已约满');
        $template->send();

        return '';
    }
    /**
     * 就诊提醒通知
     * @param Appoint $appoint
     * @return $this
     * @throws \Exception
     */
    public function AppointRemind(Appoint $appoint)
    {
        $family = $appoint->family;
        $hospital = $appoint->hospital;
        $hospital_name = Str::substr($hospital->name,0,20);
        $appoint_time = HospitalAppointInterval::query()->where('id',$appoint->appoint_time)->first();
        $type = HospitalAppointType::query()->where('id',$appoint->type)->value('name');

        $template = app(TemplateFactory::class)
            ->create('medical_reminder')
            ->to($this->openid)
            ->name($family->name)
            ->hospital($hospital_name)
            ->datetime($appoint->appoint_date." ".$appoint_time->start)
            ->info("您预约了".$type."，请按时到社区就诊");
        $template->send();

        $url = $this->url.$appoint->id;

        $teamName = isset($family) && $family->team?$family->team->name:"";
        $appoint_time = $appoint->interval;
        $content = isset($appoint_time)?$teamName."提醒您，您预约了".$appoint->appoint_date."的.".$type."请携带相关证件，于".$appoint_time->value('start')."前到达社区就诊":"";
        SubMessage::install($appoint->user_id,5,$url,$content);

        return '';
    }
    /**
     * 宣教指导通知
     * @param Appoint $appoint
     * @return $this
     * @throws \Exception
     */
    public function Edu(FamilyEdu $familyEdu)
    {
//        $data[]=(string)$familyEdu->created_at;
//        $data[]=$familyEdu->hospital->name;
//        $data[]=$familyEdu->team->name;
//        $data[]=$familyEdu->family->name;
//        $data[]=$familyEdu->familyType->name."中医药儿童健康指导";
//        $this->client_msg_id = $familyEdu->familyType->name."中医药儿童健康指导";
//
//        $response = $this->handle($data);

        $url = $this->url.$familyEdu->article_id;
        $teamName = isset($family) && $family->team?$family->team->name:"";
        $content = isset($appoint_time)?$teamName."提醒您，请于".$appoint_time->value('start')."到达社区":"";
        SubMessage::install($familyEdu->user_id,5,$url,$content);


        return true;
    }




    /**
     * 社区推送通知
     * @param  Notice $notice
     * @return $this
     * @throws \Exception
     */
    public function ArticlePush(Notice $notice)
    {
        $hospital = Hospital::query()
            ->where('id',$notice->hospital_id)
            ->first();
        $article = ArticleInfo::query()
            ->where('article_id',$notice->article_id)
            ->first();
//        $data[]=$hospital->name."签约用户";
//        $data[]=date('Y年m月d日');
//        $data[]=$hospital->name."提醒您:《".$article->title."》";
//        $this->miniprogram['pagepath'] = $this->miniprogram['pagepath'].$notice->article_id;
//
//        $response = $this->handle($data);
//        return $response;

        $url = $this->url.$notice->article_id;
        $content = $hospital->name."为您推送了一条消息:《".$article->title."》";
        SubMessage::install($this->user_id,5,$url,$content);
        return "";
    }
    /**
     * 体检提醒
     * @param Appoint $appoint
     * @return $this
     * @throws \Exception
     */
    public function examinationRemind()
    {
        $this->miniprogram =  [
            'appid' => $this->mini_appid,
            'pagepath' => 'pages/index/index?id=' . $appoint->id,
        ];
        $this->setOpenid($appoint->user_id);
        $this->setTempid('b1mjgyGxK-YzQgo3IaGARjC6rkRN3qu56iDjbD6hir4');
        $response = $this->handle(['儿童保健','儿童保健']);
        return $response;
    }
    /**
     * 追访提醒提醒
     * @param InterviewRemind $interviewRemind
     * @return $this
     * @throws \Exception
     */
    public function InterviewRemind(InterviewRemind $interviewRemind)
    {
        $family = Family::query()->where('id',$interviewRemind->family_id)->first();
        if($family){
            $data[]=$family->name;
            $data[]=date('Y年m月d日');
            $data[]=InterviewRemind::$typeTxt[$interviewRemind->type];
            $this->miniprogram['pagepath'] = $this->miniprogram['pagepath'].$family->id;

            $response = $this->handle($data);
        }
        $interviewRemind->status = 1;
        $interviewRemind->save();
        return $response;
    }
}
